package com.xpp.yanbi.utils;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * excel 相关工具类
 */
@Slf4j
public class ExcelUtils {
    /**
     * excel 转 csv
     *
     * @param multipartFile
     * @return
     */
    public static String excelToCsv(MultipartFile multipartFile) {
        // File file = null;
        // try {
        //     file = ResourceUtils.getFile("classpath:网站数据.xlsx");
        // } catch (FileNotFoundException e) {
        //     throw new RuntimeException(e);
        // }
        List<Map<Integer, String>> list = null;
        try {
            list = EasyExcel.read(multipartFile.getInputStream())
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet()
                    .headRowNumber(0)
                    .doReadSync();
        } catch (IOException e) {
            log.error("表格处理错误", e);
            throw new RuntimeException(e);
        }

        if (CollUtil.isEmpty(list)) {
            return "";
        }
        // 转换csv
        // 读取表头
        StringBuilder stringBuilder = new StringBuilder();
        Map<Integer, String> headerMap = list.get(0);
        List<String> headerList = headerMap.values().stream().filter(StringUtils::isNotBlank).collect(Collectors.toList());
        stringBuilder.append(StringUtils.join(headerList, ",") + "\n");
        // 读取数据
        for (int i = 1; i < list.size(); i++) {
            Map<Integer, String> dataMap = list.get(i);
            List<String> dataList = dataMap.values().stream().filter(StringUtils::isNotBlank).collect(Collectors.toList());
            stringBuilder.append(StringUtils.join(dataList, ",") + "\n");
        }
        // System.out.println(stringBuilder.toString());
        return stringBuilder.toString();
    }

    // public static void main(String[] args) {
    //     excelToCsv(null);
    // }
}
